package com.rfsp.mcp.controller.bank;

import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.ResultListVO;
import com.rfsp.common.base.ResultVO;
import com.rfsp.common.interceptor.Token;
import com.rfsp.common.interceptor.TokenType;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.pojo.dto.BargainDTO;
import com.rfsp.mcp.pojo.dto.SmsDTO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.mcp.pojo.sdto.BargainSDTO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.mcp.pojo.vo.BargainVO;
import com.rfsp.mcp.pojo.vo.FinanceVO;
import com.rfsp.mcp.pojo.vo.HospitalVO;
import com.rfsp.mcp.service.BargainService;
import com.rfsp.mcp.service.FinanceService;
import com.rfsp.mcp.service.HospitalService;
import com.rfsp.mcp.service.SmsLoopService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@RequiresRoles(value={"mcp_bank"}, logical= Logical.AND)
@Controller("BankBargainController")
@RequestMapping("/bank/bargain")
public class BankBargainController extends BankController {

    public Logger logger = LoggerFactory.getLogger(BankBargainController.class);

    @Autowired
    BargainService service;

    @Autowired
    HospitalService hospitalService;

    @Autowired
    FinanceService financeService;

    @Autowired
    SmsLoopService smsLoopService;

    @RequestMapping("/")
    public String index1(ModelMap model, PageSDTO pageSdto, BargainSDTO sdto) {
        return index(model,pageSdto,sdto);
    }
    @RequestMapping("/index")
    public String index(ModelMap model, PageSDTO pageSdto, BargainSDTO sdto) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankBargainController.index"));

        sdto=XssUtils.replaceXss(sdto);

        sdto.setValidity("1");
        UserPO user = ShiroUtils.getCurrentUser();
        sdto.setBankOrgId(user.getOrgId());
        PageInfo<BargainVO> page=service.list(sdto,pageSdto);
        service.combo(page.getList());
        ResultListVO<BargainVO> result = ResultListVO.success(page,sdto);
        model.put("vo", result);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankBargainController.index"));
        return "bank/bargain/index";
    }

/*
    @GetMapping("/detail")
    public String detail(ModelMap model,Long id) {
        BargainVO vo=new BargainVO();
        service.combo(vo);
        ResultVO<BargainVO> result = ResultVO.success(vo);
        model.put("vo", result);
        return "bank/bargain1/detail";
    }
*/

    @Token
    @GetMapping("/create")
    public String createForm(ModelMap model,@ModelAttribute("dto") BargainDTO dto, BindingResult bindingResult) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankBargainController.createForm"));

//        dto=XssUtils.replaceXss(dto);

        BargainVO vo=new BargainVO();
        BeanUtils.copyProperties(dto,vo);
        service.combo(vo);

        FinanceVO finance=financeService.getById(dto.getFinanceId());
        financeService.combo(finance);
        vo.setFinance(finance);

        model.put("dto",dto);

        ResultVO<BargainVO> result = ResultVO.success(vo);
        model.put("result", result);
        if(bindingResult.hasErrors()) {
            result.setMsg("操作失败");
        }
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankBargainController.createForm"));
        return "bank/bargain/createForm";
    }

    public String previewCreateForm(ModelMap model, BargainDTO dto) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankBargainController.previewCreateForm"));

        BargainVO vo=new BargainVO();
        BeanUtils.copyProperties(dto,vo);

        FinanceVO finance=financeService.getById(dto.getFinanceId());
        HospitalVO hospital=hospitalService.getById(finance.getOrgId());
        vo.setMiOrgName(hospital.getOrgName());

        service.combo(vo);
        ResultVO<BargainVO> result = ResultVO.success(vo);
        model.put("result", result);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankBargainController.previewCreateForm"));
        return "bank/bargain/previewCreateForm";
    }

    @Token(TokenType.refresh)
    @PostMapping("/create")
    public String create(ModelMap model,@ModelAttribute("dto") @Valid BargainDTO dto, BindingResult result) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankBargainController.create"));

        dto=XssUtils.replaceXss(dto);

        //获得融资申请信息
        FinanceVO finance=financeService.getById(dto.getFinanceId());
        dto.setFinanceId(finance.getId());
        dto.setPfmId(finance.getPfmId());
        dto.setMiOrgId(finance.getOrgId());
        dto.setOrgYbjId(finance.getOrgYbjId());

        //已撤销验证
        if("3".equals(finance.getFinanceStatus())){
            result.addError(new FieldError("dto", "global", "放款失败，融资申请已终止"));
            return createForm(model,dto,result);
        }
        //模拟报错流程
        //result.addError(new FieldError("dto", "loanEndTime", "提交失败"));
        if(result.hasErrors()) {
            return createForm(model,dto,result);
        }
        if("form".equals(dto.getAction())){
            return createForm(model,dto,result);
        }
        if("preview".equals(dto.getAction())){
            return this.previewCreateForm(model,dto);
        }
        if("create".equals(dto.getAction())){
            UserPO user = ShiroUtils.getCurrentUser();
            dto.setBankOrgId(user.getOrgId());
            dto.setCreateUserId(user.getId());
            dto.setOptUserId(user.getId());

            //设置放款号
            //dto.setLoanCode(service.getLoadCode(finance.getFinanceNo(),1));

            //创建
            Integer count=service.create(dto);
            if(count==0){
                result.addError(new FieldError("dto", "global", "放款失败，请联系管理员"));
                return createForm(model,dto,result);
            }

            //发送短信
            String mobile=finance.getContactMobile();
            //mobile="13820025690";
            String msg="尊敬的用户，您好！您在中征应收账款融资服务平台有新的放款信息（中征放款流水编号为"+dto.getLoanCode()+"），请及时查看，拒收请回复R。";

            //存储短信
            SmsDTO sms=new SmsDTO();
            sms.setMobile(mobile);
            sms.setContent(msg);
            sms.setUsercode(user.getUserCode());
            smsLoopService.create(sms);

            //发送短信
            //smsFeignService.sendSms(mobile, msg,sms.getSerialNumber());

            //更改融资申请状态
            financeService.updateToBargain(finance.getId(),dto);

            logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankBargainController.create"));

            return this.alertParentReloadForCreate(model,finance.getId(),"放款成功");
            //return this.alertParentReloadLocation(model,"操作成功",getContextPath()+"/base/bargain/detail/?id="+dto.getId());
        }
        //错误返回
        return createForm(model,dto,result);
    }


    protected String alertParentReloadForCreate(ModelMap model,Long financeId, String msg){
        model.put("financeId",financeId);
        model.put("msg",msg);
        return "bank/bargain/alertParentReloadForCreate";
    }
}